package com.triones.yjj.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.RandomName;
import com.ruoyi.system.mapper.SysUserMapper;
import com.triones.yjj.entity.*;
import com.triones.yjj.entity.bo.*;
import com.triones.yjj.entity.vo.*;
import com.triones.yjj.mapper.*;
import com.triones.yjj.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单相关 service 业务实现
 *
 * @Author: triones
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final OrderMapper orderMapper;

    private final GroupPurchaseGoodsItemMapper groupPurchaseGoodsItemMapper;

    private final OrderTradeRecordMapper orderTradeRecordMapper;

    private final StaffMapper staffMapper;

    private final RefundTradeMapper refundTradeMapper;

    private final GroupPurchaseGoodsMapper groupPurchaseGoodsMapper;

    private final MemberGroupPurchaseMapper memberGroupPurchaseMapper;

    private final MemberGroupPurchaseItemMapper memberGroupPurchaseItemMapper;

    private final WxUserMapper wxUserMapper;

    private final PaymentBillMapper paymentBillMapper;

    private final MemberDistributionRecordMapper memberDistributionRecordMapper;

    private final SysUserMapper baseMapper;

    @Override
    public TableDataInfo<OrderListVO> pageList(OrderListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<OrderDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id",loginUser.getUserId());
        wrapper.eq(ObjectUtil.isNotNull(params.getOrderSource()) && params.getOrderSource() != 0,"a.order_source",params.getOrderSource());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getOrderNo()),"a.order_no",params.getOrderNo());

        wrapper.and(ObjectUtil.isNotEmpty(params.getWxKeyword()),
            qw -> {
                qw.like("aw.nickname",params.getWxKeyword()).or()
                    .like("aw.nickname",params.getWxKeyword()).or()
                    .like("aw.id",params.getWxKeyword());
            }
        );

        wrapper.and(ObjectUtil.isNotEmpty(params.getEnrollKeyword()),
            qw -> {
                qw.like("a.enroll_name",params.getEnrollKeyword()).or()
                    .like("a.enroll_mobile",params.getEnrollKeyword());
            }
        );

        wrapper.and(ObjectUtil.isNotEmpty(params.getGoodsName()),
            qw -> {
                qw.like("b.goods_name",params.getGoodsName()).or()
                    .like("b.goods_subtitle",params.getGoodsName()).or()
                    .like("bi.welfare_name",params.getGoodsName());
            }
        );

        wrapper.eq(ObjectUtil.isNotNull(params.getActivityId()),"a.activity_id",params.getActivityId());
        wrapper.eq(ObjectUtil.isNotNull(params.getOrderStatus()),"a.status",params.getOrderStatus());
        wrapper.isNotNull(ObjectUtil.isNotNull(params.getSplicingType()) && params.getSplicingType() == 1,"a.group_purchase_id");
        wrapper.isNull(ObjectUtil.isNotNull(params.getSplicingType()) && params.getSplicingType() == 2,"a.group_purchase_id");

        wrapper.and(ObjectUtil.isNotNull(params.getDistributionType()) && params.getDistributionType() == 1,
            qw -> {
                qw.gt("a.one_distribution_amount",0).or()
                    .gt("a.two_distribution_amount",0);
            }
        );

        wrapper.isNull(ObjectUtil.isNotNull(params.getDistributionType()) && params.getDistributionType() == 2,"a.one_distribution_amount");
        wrapper.isNull(ObjectUtil.isNotNull(params.getDistributionType()) && params.getDistributionType() == 2,"a.two_distribution_amount");
        if (params.getOrderCreateTimeRange() != null && params.getOrderCreateTimeRange().size() > 0) {
            wrapper.between("a.create_time",params.getOrderCreateTimeRange().get(0),params.getOrderCreateTimeRange().get(1));
        }
        if (params.getVerificationTimeRange() != null && params.getVerificationTimeRange().size() > 0) {
            wrapper.between("a.verification_time",params.getVerificationTimeRange().get(0),params.getVerificationTimeRange().get(1));
        }
        wrapper.like(ObjectUtil.isNotEmpty(params.getOneDistributionNickname()),"dw.nickname",params.getOneDistributionNickname());
        wrapper.like(ObjectUtil.isNotEmpty(params.getTwoDistributionNickname()),"ew.nickname",params.getTwoDistributionNickname());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getNature()),"c.status",params.getNature());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getTeamLeaderNickname()),"cw.nickname",params.getTeamLeaderNickname());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getIdentity()),"ci.identity",params.getIdentity());
        wrapper.eq(ObjectUtil.isNotNull(params.getTeamStatus()) && params.getTeamStatus() != 0,"c.status",params.getTeamStatus());
        wrapper.eq(ObjectUtil.isNotNull(params.getCollectionChannel()),"a.collection_channel",params.getCollectionChannel());
        wrapper.eq(ObjectUtil.isNotNull(params.getCollectionMiniApp()),"a.collection_mini_app",params.getCollectionMiniApp());
        wrapper.orderByDesc("a.create_time","a.verification_time");
        Page<OrderListVO> result = orderMapper.pageList(pageQuery.build(),wrapper);
        if (result.getRecords().size() > 0) {
            result.getRecords().forEach(item -> {
                item.setGoodsItemList(groupPurchaseGoodsItemMapper.selectVoList(new LambdaQueryWrapper<GroupPurchaseGoodsItemDO>()
                    .eq(GroupPurchaseGoodsItemDO::getGroupPurchaseGoodsId, item.getGroupPurchaseGoodsId())));
            });
        }
        return TableDataInfo.build(result);
    }

    @Override
    public Map stats(OrderListParams params) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        Map map = new HashMap();
        /**
         * 获取订单总数
         */
        Long orderTotal = orderMapper.selectCount(new LambdaQueryWrapper<OrderDO>().eq(OrderDO::getUserId, loginUser.getUserId()));
        map.put("orderTotal", Convert.toInt(orderTotal,0));
        /**
         * 支付总额
         */
        String statsAmountTotal = orderMapper.statsAmountTotal(loginUser.getUserId());
        map.put("statsAmountTotal", Convert.toBigDecimal(statsAmountTotal,BigDecimal.ZERO));
        /**
         * 佣金+返利+员工奖励+微信实收手续费总额
         */
        String statsDeductTotalAmount = orderMapper.statsDeductTotalAmount(loginUser.getUserId());
        map.put("statsDeductTotalAmount", Convert.toBigDecimal(statsDeductTotalAmount,BigDecimal.ZERO));

        /**
         * 可提现总金额
         */
        List<OrderDO> dos = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
            .eq(OrderDO::getUserId, loginUser.getUserId()).in(OrderDO::getStatus, 2, 5));
        map.put("withdrawableAmount", BigDecimal.ZERO);
        if (dos.size() > 0) {
            BigDecimal withdrawableAmount = dos.stream().filter(s -> ObjectUtil.isNotNull(s.getActualAmount())).collect(Collectors.toList())
                .stream().map(OrderDO::getActualAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            map.put("withdrawableAmount", withdrawableAmount);
        }
        return map;
    }
   public WxMemberOrderVoucherVO getMemberOrderVoucher(Long memberId){
       WxMemberOrderVoucherVO memberOrderVoucherVO = new WxMemberOrderVoucherVO();
       //报名凭证
       List<WxMemberOrderVO> orderList= orderMapper.getMemberOrderList(memberId);
       memberOrderVoucherVO.setOrderList(orderList);
       //礼品凭证
       WxMemberInviteRewardVO inviteRewardVO = orderMapper.getMemberRewardInfo(memberId);
       memberOrderVoucherVO.setMemberInviteRewardVO(inviteRewardVO);
       return memberOrderVoucherVO;
   }

   public List<ActivityOrderUserVO> getActivityOrderMemberList(Long activityId){
       List<ActivityOrderUserVO> orderUserList= orderMapper.getActivityOrderMemberList(activityId);
       return orderUserList;
   }

    public List<ActivityOrderUserVO> getActivityAllOrderList(Long activityId){
        List<ActivityOrderUserVO> orderUserList= orderMapper.getActivityAllOrderList(activityId);
        return orderUserList;
    }

    @Override
    public OrderDetailVO detailById(Long orderId) {
        OrderDetailVO vo = new OrderDetailVO();
        OrderVO orderVO = orderMapper.selectVoById(orderId);
        if (orderVO != null) {
            vo.setOrderVO(orderVO);
            /**
             * 微信信息
             */
            WxUserVO wxUserVO = wxUserMapper.selectVoById(orderVO.getMemberWxUserId());
            vo.setWxUserVO(wxUserVO);
            /**
             * 支付信息
             */
            LambdaQueryWrapper<PaymentBillDO> paymentBillWrapper = Wrappers.lambdaQuery(PaymentBillDO.class);
            paymentBillWrapper.eq(PaymentBillDO::getOrderNo,orderVO.getOrderNo());
            PaymentBillVO paymentBillVO = paymentBillMapper.selectVoOne(paymentBillWrapper);
            vo.setPaymentBillVO(paymentBillVO);
            /**
             * 退款信息
             */
            LambdaQueryWrapper<RefundTradeDO> refundWrapper = Wrappers.lambdaQuery(RefundTradeDO.class);
            refundWrapper.eq(RefundTradeDO::getOrderNo,orderVO.getOrderNo());
            RefundTradeVO refundTradeVO = refundTradeMapper.selectVoOne(refundWrapper);
            vo.setRefundTradeVO(refundTradeVO);
            /**
             * 商品信息
             */
            GroupPurchaseGoodsVO groupPurchaseGoodsVO = groupPurchaseGoodsMapper.selectVoById(orderVO.getGroupPurchaseGoodsId());
            vo.setGroupPurchaseGoodsVO(groupPurchaseGoodsVO);
            /**
             * 商品阶梯信息
             */
            LambdaQueryWrapper<GroupPurchaseGoodsItemDO> goodsItemWrapper = Wrappers.lambdaQuery(GroupPurchaseGoodsItemDO.class);
            goodsItemWrapper.eq(GroupPurchaseGoodsItemDO::getGroupPurchaseGoodsId,orderVO.getGroupPurchaseGoodsId());
            List<GroupPurchaseGoodsItemVO> goodsItemList = groupPurchaseGoodsItemMapper.selectVoList(goodsItemWrapper);
            vo.setGoodsItemList(goodsItemList);
            /**
             * 拼团信息
             */
            MemberGroupPurchaseVO memberGroupPurchaseVO = memberGroupPurchaseMapper.selectVoById(orderVO.getGroupPurchaseId());
            vo.setMemberGroupPurchaseVO(memberGroupPurchaseVO);
            /**
             * 拼团内信息
             */
            List<MemberGroupPurchaseItemListVO> itemList = memberGroupPurchaseItemMapper.getItemList(orderVO.getGroupPurchaseId());
            vo.setGroupPurchaseItemList(itemList);
            /**
             * 核销员工信息
             */
            if (orderVO.getVerificationStaffId() != null) {
                StaffVO verificationStaff = new StaffVO();
                if (orderVO.getVerificationStaffId() == -1) {
                    verificationStaff.setRealname("主账号");
                } else {
                    verificationStaff = staffMapper.selectVoById(orderVO.getVerificationStaffId());
                }
                vo.setVerificationStaff(verificationStaff);
            }
        }
        return vo;
    }

    @Override
    public TableDataInfo<OrderListVO> bringOrderPageList(MemberBringOrderListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<OrderDO> wrapper = Wrappers.query();
        wrapper.eq("t.user_id",loginUser.getUserId());
        wrapper.eq("t.activity_id",params.getActivityId());
        wrapper.eq("ts.member_id",params.getMemberId());
        wrapper.in("t.status",2,5);
        wrapper.orderByDesc("t.create_time");
        Page<OrderListVO> result = orderMapper.bringOrderPageList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    public TableDataInfo<ActivityOrderUserVO> getActivityPayOrderList(Long activityId, PageQuery pageQuery) {
        QueryWrapper<OrderDO> wrapper = new QueryWrapper<>();
        // 默认排序 时间倒叙
        if (StringUtils.isBlank(pageQuery.getOrderByColumn()) || StringUtils.isBlank(pageQuery.getIsAsc())) {
            wrapper.lambda().orderByDesc(OrderDO::getCreateTime);
        }
        wrapper.in("o.`status`",2,5);
        wrapper.eq("o.activity_id", activityId);
        Page<ActivityOrderUserVO> result = orderMapper.getActivityPayOrderList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    public Long orderCount(WxStaffDetailVO staffVO,Long activityId,Boolean today){
        QueryWrapper<OrderDO> wrapper = new QueryWrapper<>();
        wrapper.eq("performance_staff_id",staffVO.getId());
        wrapper.eq("activity_id",activityId);
        wrapper.eq("user_id",staffVO.getUserId());
        wrapper.in("status",2,5);
        wrapper.eq(today," DATE_FORMAT(create_time, '%Y-%m-%d')", DateUtil.getDay());
        return orderMapper.selectCount(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public R<T> staffVerificationOrder(WxStaffDetailVO staffVO, Long orderId){
        StaffVO staffVO1 = staffMapper.selectVoById(staffVO.getId());
        if (ObjectUtil.isEmpty(staffVO1)) {
            return R.fail("员工不存在");
        }
        if (!staffVO1.getIsVerification().equals(1)) {
            return R.fail("员工暂无核销权限");
        }
        OrderDO orderDO = orderMapper.selectOne(new LambdaQueryWrapper<OrderDO>().eq(OrderDO::getId,orderId));
        if (ObjectUtil.isEmpty(orderDO)) {
            return R.fail("订单不存在");
        }
        SysUser sysUser = baseMapper.selectById(orderDO.getUserId());
        if(orderDO.getStatus().intValue()!=2){
            return  R.fail("该订单不能核销");
        }
        UpdateWrapper<OrderDO> wrapper = new UpdateWrapper<>();
        wrapper.set("status",5);
        wrapper.set("settlement_status",2);
        wrapper.set("verification_staff_id",staffVO.getId());
        wrapper.set("verification_time",DateUtil.getDateTimeString());

        verificationDistribution(orderDO);
        wrapper.eq("id",orderDO.getId());
        orderMapper.update(orderDO,wrapper);

        /**
         * 商家结算至待清算金额里面
         */
        sysUser.setWaitSettlementAmount(sysUser.getWaitSettlementAmount().add(orderDO.getActualAmount()));
        baseMapper.updateById(sysUser);
        return R.ok("核销成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean orderVerification(OrderDO dto) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        OrderDO orderDO = orderMapper.selectOne(new LambdaQueryWrapper<>(OrderDO.class)
            .eq(OrderDO::getId,dto.getId()).eq(OrderDO::getStatus,2));
        if (orderDO == null) {
            throw new SecurityException("订单不存在");
        }
        if (!dto.getVerificationCode().equals(orderDO.getVerificationCode())) {
            throw new SecurityException("核销码错误");
        }
        orderDO.setVerificationTime(DateUtil.getDateTimeString());
        orderDO.setStatus(5);
        orderDO.setSettlementStatus(2);
        /**
         * 给商家结算
         */
        SysUser sysUser = baseMapper.selectById(orderDO.getUserId());
        if (sysUser == null) {
            throw new ServiceException("没有查询到商家信息");
        }
        sysUser.setWaitSettlementAmount(sysUser.getWaitSettlementAmount().add(orderDO.getActualAmount()));
        baseMapper.updateById(sysUser);
        // -1 表示主账号核销
        orderDO.setVerificationStaffId(-1L);
        verificationDistribution(orderDO);
        return orderMapper.updateById(orderDO) > 0;
    }

    public OrderDO getOrderByNo(String orderNo){
        QueryWrapper<OrderDO> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        return orderMapper.selectOne(wrapper);
    }
    public OrderDO getOrderByVerificationCode(String verificationCode){
        QueryWrapper<OrderDO> wrapper = new QueryWrapper<>();
        wrapper.eq("verification_code",verificationCode);
        return orderMapper.selectOne(wrapper);
    }
    public List<ActivityOrderUserVO> getVerificationOrderList(Long activityId,Long memberId){
//        QueryWrapper<OrderDO> wrapper = Wrappers.query();
//        wrapper.eq("activity_id",activityId);
//        wrapper.eq("member_id",memberId);
//        wrapper.eq("status",2);
//        return orderMapper.selectVoList(wrapper,OrderVO.class);
        return orderMapper.getMemberVerOrderList(activityId,memberId);
    }

    public R<T> memberVerificationOrder(MemberDetailVO memberDetailVO, Long orderId, Long staffId) {
        StaffVO staffVO = staffMapper.selectVoById(staffId);
        if (ObjectUtil.isEmpty(staffVO)) {
            return R.fail("员工不存在");
        }
        if (!staffVO.getIsVerification().equals(1)) {
            return R.fail("员工暂无核销权限");
        }
        OrderDO orderDO = orderMapper.selectOne(new LambdaQueryWrapper<OrderDO>().eq(OrderDO::getId,orderId)
            .eq(OrderDO::getMemberId,memberDetailVO.getId()));
        if (ObjectUtil.isEmpty(orderDO)) {
            return R.fail("订单不存在");
        }
        if (orderDO.getStatus().intValue() != 2) {
            return R.fail("该订单不能核销");
        }
        UpdateWrapper<OrderDO> wrapper = new UpdateWrapper<>();
        wrapper.set("status", 5);
        wrapper.set("settlement_status", 2);
        wrapper.set("verification_staff_id", staffId);
        wrapper.set("verification_time", DateUtil.getDateTimeString());

        verificationDistribution(orderDO);
        wrapper.eq("id",orderDO.getId());
        orderMapper.update(orderDO, wrapper);
        return R.ok("核销成功");
    }

    public TableDataInfo<WxVerificationOrderVO> getVerificationOrderList(WxVerificationOrderParams params, PageQuery pageQuery) {
        QueryWrapper<OrderDO> wrapper = Wrappers.query();
        wrapper.eq("a.verification_staff_id",params.getStaffId());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getActivityId()),"a.activity_id",params.getActivityId());
        wrapper.ge(ObjectUtil.isNotNull(params.getStartDate()),"a.verification_time",params.getStartDate()+" 00:00:00")
            .or().le(ObjectUtil.isNotNull(params.getEndDate()),"a.verification_time",params.getEndDate()+" 00:00:00");
        wrapper.like(ObjectUtil.isNotEmpty(params.getKeyWord()),"a.enroll_name",params.getKeyWord()).or()
            .like(ObjectUtil.isNotEmpty(params.getKeyWord()),"a.enroll_mobile",params.getKeyWord());
        wrapper.orderByDesc("a.verification_time");
        Page<WxVerificationOrderVO> result = orderMapper.getVerificationOrderList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 核销的分销明细
     * @param orderDO
     */
    private void verificationDistribution(OrderDO orderDO){
        /**
         * 处理明细记录
         */
        List<OrderTradeRecordDO> tradeRecordList = new ArrayList<>();

        /**
         * 删除待结算的订单交易记录
         */
        orderTradeRecordMapper.delete(new LambdaQueryWrapper<OrderTradeRecordDO>()
            .eq(OrderTradeRecordDO::getOrderId,orderDO.getId()).eq(OrderTradeRecordDO::getSettlementStatus,1));

        // 收入-全额
        OrderTradeRecordDO amountTradeRecord = new OrderTradeRecordDO();
        amountTradeRecord.setOrderId(orderDO.getId());
        amountTradeRecord.setFundType("order_settled");
        amountTradeRecord.setTradeAmount(orderDO.getRealityPayAmount());
        amountTradeRecord.setMemberId(orderDO.getMemberId());
        amountTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
        amountTradeRecord.setSettlementStatus(2);
        amountTradeRecord.setUserId(orderDO.getUserId());
        tradeRecordList.add(amountTradeRecord);
        // 手续费
        OrderTradeRecordDO commissionTradeRecord = new OrderTradeRecordDO();
        commissionTradeRecord.setOrderId(orderDO.getId());
        commissionTradeRecord.setFundType("charge_deduction");
        commissionTradeRecord.setTradeAmount(orderDO.getCommission().negate());
        commissionTradeRecord.setMemberId(orderDO.getMemberId());
        commissionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
        commissionTradeRecord.setSettlementStatus(2);
        commissionTradeRecord.setUserId(orderDO.getUserId());
        tradeRecordList.add(commissionTradeRecord);
        // 分销佣金（一级）
        Long twoShareRecordId =0L;
        //查询分享记录
        if (orderDO.getOneDistributionAmount() != null && orderDO.getOneDistributionAmount().compareTo(BigDecimal.ZERO) == 1) {
            OrderTradeRecordDO oneDistributionTradeRecord = new OrderTradeRecordDO();
            oneDistributionTradeRecord.setOrderId(orderDO.getId());
            oneDistributionTradeRecord.setFundType("invite_deduction");
            oneDistributionTradeRecord.setTradeAmount(orderDO.getOneDistributionAmount().negate());
            oneDistributionTradeRecord.setMemberId(orderDO.getMemberId());
            oneDistributionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
            oneDistributionTradeRecord.setSettlementStatus(2);
            oneDistributionTradeRecord.setUserId(orderDO.getUserId());
            tradeRecordList.add(oneDistributionTradeRecord);
        }
        // 分销佣金（二级）
        if (orderDO.getTwoDistributionAmount() != null && orderDO.getTwoDistributionAmount().compareTo(BigDecimal.ZERO) == 1) {
            OrderTradeRecordDO twoDistributionTradeRecord = new OrderTradeRecordDO();
            twoDistributionTradeRecord.setOrderId(orderDO.getId());
            twoDistributionTradeRecord.setFundType("invite_deduction");
            twoDistributionTradeRecord.setTradeAmount(orderDO.getTwoDistributionAmount().negate());
            twoDistributionTradeRecord.setMemberId(orderDO.getMemberId());
            twoDistributionTradeRecord.setMemberWxUserId(orderDO.getMemberWxUserId());
            twoDistributionTradeRecord.setSettlementStatus(2);
            twoDistributionTradeRecord.setUserId(orderDO.getUserId());
            tradeRecordList.add(twoDistributionTradeRecord);
        }
        orderTradeRecordMapper.insertBatch(tradeRecordList);

    }


    public TableDataInfo<WxStaffOrderVO> orderList(WxStaffDetailVO wxStaffDetailVO, PageQuery pageQuery) {
        QueryWrapper<OrderDO> wrapper = Wrappers.query();
        wrapper.eq("a.member_id",wxStaffDetailVO.getMemberId());
        wrapper.orderByDesc("a.create_time");
        Page<WxStaffOrderVO> result = orderMapper.getOrderList(pageQuery.build(),wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Map<String, Object> activityIsEnroll(MemberDetailVO memberDetailVO, Long activityId) {
        Map<String,Object> map = new HashMap<>();
        map.put("isEnroll",false);
        LambdaQueryWrapper<OrderDO> wrapper = Wrappers.lambdaQuery(OrderDO.class);
        wrapper.in(OrderDO::getStatus,2,5)
            .eq(OrderDO::getActivityId,activityId)
            .eq(OrderDO::getMemberId,memberDetailVO.getId());
        Long count = orderMapper.selectCount(wrapper);
        if (count != null && count > 0) {
            map.put("isEnroll",true);
        }
        logger.info("查询是否成功报名" + map.get("isEnroll"));
        return map;
    }

    /**
     * 定时处理未付款的订单
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void handleUnpaidOrder() {
        LambdaQueryWrapper<OrderDO> wrapper = Wrappers.lambdaQuery(OrderDO.class);
        wrapper.eq(OrderDO::getStatus,1);
        List<OrderDO> list = orderMapper.selectList(wrapper);
        if (list != null && list.size() > 0) {
            long currentStamp = DateUtil.getDateline();
            for (OrderDO orderDO : list) {
                long createStamp = DateUtil.getDateline(orderDO.getCreateTime()) + 2 * 60 * 60;
                if (createStamp < currentStamp) {
                    orderDO.setStatus(4);
                    orderDO.setCloseReason("超时关闭");
                    orderDO.setUpdateTime(DateUtil.getDateTime());
                    orderMapper.updateById(orderDO);
                }
            }
        }
    }

    public ActivityOrderUserVO getActivityOrderDetail(Long id){
        return orderMapper.getOrderDetail(id);
    }

    public TableDataInfo<WxStaffMemberOrderVO> getStaffMemberOrderList(WxStaffMemberOrderParams params, PageQuery pageQuery) {
        Page<WxStaffMemberOrderVO> result = orderMapper.getStaffMemberOrderList(pageQuery.build(),params);
       List<WxStaffMemberOrderVO> list =  result.getRecords();
       if(ObjectUtil.isNotEmpty(list)&&list.size()>0){
           for (WxStaffMemberOrderVO wxStaffMemberOrderVO:list){
               if(wxStaffMemberOrderVO.getPerformanceStaffId().equals(wxStaffMemberOrderVO.getInviteStaffId())){
                   wxStaffMemberOrderVO.setMemberType(1);
               }else{
                   wxStaffMemberOrderVO.setMemberType(2);
               }
               wxStaffMemberOrderVO.setMemberGroupPurchaseItemList(memberGroupPurchaseItemMapper.getItemList(wxStaffMemberOrderVO.getGroupPurchaseId()));
           }
       }
        result.setRecords(list);
        return TableDataInfo.build(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean upgrade(Long orderId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        OrderDO orderDO = orderMapper.selectById(orderId);
        if (orderDO == null) {
            throw new ServiceException("订单不存在");
        }
        MemberGroupPurchaseItemDO memberGroupPurchaseItemDO = memberGroupPurchaseItemMapper.selectById(orderDO.getGroupPurchaseItemId());
        if (memberGroupPurchaseItemDO == null) {
            throw new ServiceException("拼团信息不存在");
        }
        if (memberGroupPurchaseItemDO.getIdentity() != 2) {
            throw new ServiceException("该用户不是团员");
        }
        MemberGroupPurchaseDO memberGroupPurchaseDO = memberGroupPurchaseMapper.selectById(orderDO.getGroupPurchaseId());
        if (memberGroupPurchaseDO == null) {
            throw new ServiceException("拼团信息不存在");
        }

        /**
         * 查询拼团内信息列表
         */
        LambdaQueryWrapper<MemberGroupPurchaseItemDO> wrapper = Wrappers.lambdaQuery(MemberGroupPurchaseItemDO.class);
        wrapper.eq(MemberGroupPurchaseItemDO::getGroupPurchaseId,orderDO.getGroupPurchaseId())
            .eq(MemberGroupPurchaseItemDO::getIsNullify,0)
            .orderByAsc(MemberGroupPurchaseItemDO::getCreateTime);
        List<MemberGroupPurchaseItemDO> purchaseItemDOS = memberGroupPurchaseItemMapper.selectList(wrapper);
        if (purchaseItemDOS == null || purchaseItemDOS.size() <= 1) {
            throw new ServiceException("参团人数少于两人，无法升为团长或降为团员");
        }
        UpdateWrapper<MemberGroupPurchaseItemDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("identity", 2);
        updateWrapper.eq("group_purchase_id", memberGroupPurchaseItemDO.getGroupPurchaseId());
        memberGroupPurchaseItemMapper.update(null,updateWrapper);

        memberGroupPurchaseItemDO.setIdentity(1);
        memberGroupPurchaseItemMapper.updateById(memberGroupPurchaseItemDO);

        memberGroupPurchaseDO.setTeamName(memberGroupPurchaseItemDO.getRegisterName());
        memberGroupPurchaseDO.setMemberId(memberGroupPurchaseItemDO.getMemberId());
        memberGroupPurchaseDO.setMemberWxUserId(memberGroupPurchaseItemDO.getMemberWxUserId());
        return memberGroupPurchaseMapper.updateById(memberGroupPurchaseDO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean reduce(Long orderId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        OrderDO orderDO = orderMapper.selectById(orderId);
        if (orderDO == null) {
            throw new ServiceException("订单不存在");
        }
        MemberGroupPurchaseItemDO memberGroupPurchaseItemDO = memberGroupPurchaseItemMapper.selectById(orderDO.getGroupPurchaseItemId());
        if (memberGroupPurchaseItemDO == null) {
            throw new ServiceException("拼团信息不存在");
        }
        if (memberGroupPurchaseItemDO.getIdentity() != 1) {
            throw new ServiceException("该用户不是团长");
        }
        MemberGroupPurchaseDO memberGroupPurchaseDO = memberGroupPurchaseMapper.selectById(orderDO.getGroupPurchaseId());
        if (memberGroupPurchaseDO == null) {
            throw new ServiceException("拼团信息不存在");
        }
        /**
         * 查询拼团内信息列表
         */
        LambdaQueryWrapper<MemberGroupPurchaseItemDO> wrapper = Wrappers.lambdaQuery(MemberGroupPurchaseItemDO.class);
        wrapper.eq(MemberGroupPurchaseItemDO::getGroupPurchaseId,orderDO.getGroupPurchaseId())
            .eq(MemberGroupPurchaseItemDO::getIsNullify,0)
            .orderByAsc(MemberGroupPurchaseItemDO::getCreateTime);
        List<MemberGroupPurchaseItemDO> purchaseItemDOS = memberGroupPurchaseItemMapper.selectList(wrapper);
        // 新的团长信息
        MemberGroupPurchaseItemDO newMemberGroupPurchaseItemDO = null;
        if (purchaseItemDOS == null || purchaseItemDOS.size() <= 1) {
            throw new ServiceException("参团人数少于两人，无法升为团长或降为团员");
        } else {
            newMemberGroupPurchaseItemDO = purchaseItemDOS.get(0);
        }

        if (newMemberGroupPurchaseItemDO != null) {
            memberGroupPurchaseItemDO.setIdentity(2);
            memberGroupPurchaseItemMapper.updateById(memberGroupPurchaseItemDO);

            memberGroupPurchaseDO.setTeamName(newMemberGroupPurchaseItemDO.getRegisterName());
            memberGroupPurchaseDO.setMemberId(newMemberGroupPurchaseItemDO.getMemberId());
            memberGroupPurchaseDO.setMemberWxUserId(newMemberGroupPurchaseItemDO.getMemberWxUserId());
            memberGroupPurchaseMapper.updateById(memberGroupPurchaseDO);

            newMemberGroupPurchaseItemDO.setIdentity(1);
            memberGroupPurchaseItemMapper.updateById(newMemberGroupPurchaseItemDO);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean isolate(Long orderId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        OrderDO orderDO = orderMapper.selectById(orderId);
        if (orderDO == null) {
            throw new ServiceException("订单不存在");
        }
        MemberGroupPurchaseItemDO memberGroupPurchaseItemDO = memberGroupPurchaseItemMapper.selectById(orderDO.getGroupPurchaseItemId());
        if (memberGroupPurchaseItemDO == null) {
            throw new ServiceException("拼团信息不存在");
        }
        MemberGroupPurchaseDO memberGroupPurchaseDO = memberGroupPurchaseMapper.selectById(orderDO.getGroupPurchaseId());
        if (memberGroupPurchaseDO == null) {
            throw new ServiceException("拼团信息不存在");
        }
        /**
         * 查询拼团内信息列表
         */
        LambdaQueryWrapper<MemberGroupPurchaseItemDO> wrapper = Wrappers.lambdaQuery(MemberGroupPurchaseItemDO.class);
        wrapper.eq(MemberGroupPurchaseItemDO::getGroupPurchaseId,orderDO.getGroupPurchaseId())
            .eq(MemberGroupPurchaseItemDO::getIsNullify,0)
            .ne(MemberGroupPurchaseItemDO::getId,memberGroupPurchaseItemDO.getId())
            .orderByAsc(MemberGroupPurchaseItemDO::getCreateTime);
        List<MemberGroupPurchaseItemDO> purchaseItemDOS = memberGroupPurchaseItemMapper.selectList(wrapper);
        if (purchaseItemDOS != null && purchaseItemDOS.size() <= 0) {
            throw new ServiceException("当前团不能独立成团");
        }

        /**
         * 处理 独立的用户团
         */
        MemberGroupPurchaseDO newMemberGroupPurchaseDO = new MemberGroupPurchaseDO();
        newMemberGroupPurchaseDO.setPersonnelNumber(1);
        newMemberGroupPurchaseDO.setTeamName(memberGroupPurchaseItemDO.getRegisterName());
        newMemberGroupPurchaseDO.setGroupPurchaseGoodsId(memberGroupPurchaseDO.getGroupPurchaseGoodsId());
        newMemberGroupPurchaseDO.setMaxPersonnelNumber(memberGroupPurchaseDO.getMaxPersonnelNumber());
        newMemberGroupPurchaseDO.setActivityId(memberGroupPurchaseDO.getActivityId());
        newMemberGroupPurchaseDO.setUserId(memberGroupPurchaseDO.getUserId());
        newMemberGroupPurchaseDO.setMemberId(memberGroupPurchaseItemDO.getMemberId());
        newMemberGroupPurchaseDO.setMemberWxUserId(memberGroupPurchaseItemDO.getMemberWxUserId());
        this.computeGroupPurchaseGoods(newMemberGroupPurchaseDO);
        memberGroupPurchaseMapper.insert(newMemberGroupPurchaseDO);

        memberGroupPurchaseItemDO.setGroupPurchaseId(newMemberGroupPurchaseDO.getId());
        memberGroupPurchaseItemDO.setIdentity(1);
        memberGroupPurchaseItemMapper.updateById(memberGroupPurchaseItemDO);

        /**
         * 处理独立出来的订单
         */
        orderDO.setGroupPurchaseGoodsItemId(newMemberGroupPurchaseDO.getGroupPurchaseGoodsItemId());
        orderDO.setGroupPurchaseId(newMemberGroupPurchaseDO.getId());
        orderMapper.updateById(orderDO);

        /**
         * 处理剩下的团
         */
        MemberGroupPurchaseItemDO newMemberGroupPurchaseItemDO = null;
        if (memberGroupPurchaseItemDO.getIdentity() == 1 && memberGroupPurchaseDO.getMemberId().equals(memberGroupPurchaseItemDO.getMemberId())) {
            //是团长
            newMemberGroupPurchaseItemDO = purchaseItemDOS.get(0);
            memberGroupPurchaseDO.setMemberId(newMemberGroupPurchaseItemDO.getMemberId());
            memberGroupPurchaseDO.setMemberWxUserId(newMemberGroupPurchaseItemDO.getMemberWxUserId());
            memberGroupPurchaseDO.setTeamName(newMemberGroupPurchaseItemDO.getRegisterName());
            newMemberGroupPurchaseItemDO.setIdentity(1);
            memberGroupPurchaseItemMapper.updateById(newMemberGroupPurchaseItemDO);
        }
        memberGroupPurchaseDO.setPersonnelNumber(memberGroupPurchaseDO.getPersonnelNumber() - 1);
        this.computeGroupPurchaseGoods(memberGroupPurchaseDO);
        memberGroupPurchaseMapper.updateById(memberGroupPurchaseDO);
        /**
         * 处理受影响的订单
         */
        LambdaQueryWrapper<OrderDO> orderLqw = Wrappers.lambdaQuery(OrderDO.class);
        orderLqw.eq(OrderDO::getGroupPurchaseId,memberGroupPurchaseDO.getId()).in(OrderDO::getStatus,2,5);
        List<OrderDO> orderDOS = orderMapper.selectList(orderLqw);
        if (orderDOS != null && orderDOS.size() > 0) {
            for (OrderDO aDo : orderDOS) {
                aDo.setGroupPurchaseGoodsItemId(memberGroupPurchaseDO.getGroupPurchaseGoodsItemId());
            }
            orderMapper.updateBatchById(orderDOS);
        }
        return true;
    }

    @Override
    public TableDataInfo<DistributionOrderVO> distributionOrderPageList(MemberDistributionParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        params.setUserId(loginUser.getUserId());
        Page<DistributionOrderVO> result = memberDistributionRecordMapper.distributionOrderPageList(pageQuery.build(),params);
        return TableDataInfo.build(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean moveToTeam(Long groupPurchaseId, Long orderId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        /**
         * 目标团信息
         */
        MemberGroupPurchaseDO targetMemberGroupPurchaseDO = memberGroupPurchaseMapper.selectById(groupPurchaseId);
        if (targetMemberGroupPurchaseDO == null) {
            throw new ServiceException("拼团不存在");
        }
        if (targetMemberGroupPurchaseDO.getStatus() == 3) {
            throw new ServiceException("团人员已满，不能移至该团中");
        }
        OrderDO orderDO = orderMapper.selectById(orderId);
        if (orderDO == null) {
            throw new ServiceException("该用户订单异常，不支持移团");
        }
        if (orderDO.getStatus() == 1 || orderDO.getStatus() == 3 || orderDO.getStatus() == 4) {
            throw new ServiceException("该用户订单异常，不支持移团");
        }
        /**
         * 移动前拼团信息
         */
        MemberGroupPurchaseDO oldMemberGroupPurchaseDO = memberGroupPurchaseMapper.selectById(orderDO.getGroupPurchaseId());
        if (oldMemberGroupPurchaseDO == null) {
            throw new ServiceException("拼团不存在");
        }
        MemberGroupPurchaseItemDO oldMemberGroupPurchaseItemDO = memberGroupPurchaseItemMapper.selectById(orderDO.getGroupPurchaseItemId());
        if (oldMemberGroupPurchaseItemDO == null) {
            throw new ServiceException("拼团不存在");
        }
        /**
         * 查询拼团内信息列表
         */
        LambdaQueryWrapper<MemberGroupPurchaseItemDO> oldLqw = Wrappers.lambdaQuery(MemberGroupPurchaseItemDO.class);
        oldLqw.eq(MemberGroupPurchaseItemDO::getGroupPurchaseId,orderDO.getGroupPurchaseId())
            .eq(MemberGroupPurchaseItemDO::getIsNullify,0)
            .ne(MemberGroupPurchaseItemDO::getId,oldMemberGroupPurchaseItemDO.getId())
            .orderByAsc(MemberGroupPurchaseItemDO::getCreateTime);
        List<MemberGroupPurchaseItemDO> oldPurchaseItemDOS = memberGroupPurchaseItemMapper.selectList(oldLqw);

        /**
         * 处理变动后之前所在的团
         */
        MemberGroupPurchaseItemDO newMemberGroupPurchaseItemDO = null;
        oldMemberGroupPurchaseDO.setPersonnelNumber(oldMemberGroupPurchaseDO.getPersonnelNumber() - 1);
        this.computeGroupPurchaseGoods(oldMemberGroupPurchaseDO);
        //是团长
        if (oldMemberGroupPurchaseItemDO.getIdentity() == 1) {
            if (oldPurchaseItemDOS != null && oldPurchaseItemDOS.size() > 0) {
                newMemberGroupPurchaseItemDO = oldPurchaseItemDOS.get(0);
                newMemberGroupPurchaseItemDO.setIdentity(1);
                memberGroupPurchaseItemMapper.updateById(newMemberGroupPurchaseItemDO);
            }
            /**
             * 作废该主团
             */
            oldMemberGroupPurchaseDO.setStatus(-1);
        }
        memberGroupPurchaseMapper.updateById(oldMemberGroupPurchaseDO);
        MemberGroupPurchaseDO newMemberGroupPurchaseDO = new MemberGroupPurchaseDO();
        if (newMemberGroupPurchaseItemDO != null) {
            /**
             * 创建新的主团
             */
            newMemberGroupPurchaseDO.setTeamName(newMemberGroupPurchaseItemDO.getRegisterName());
            newMemberGroupPurchaseDO.setMaxPersonnelNumber(oldMemberGroupPurchaseDO.getMaxPersonnelNumber());
            newMemberGroupPurchaseDO.setPersonnelNumber(oldMemberGroupPurchaseDO.getPersonnelNumber() - 1);
            newMemberGroupPurchaseDO.setNature(oldMemberGroupPurchaseDO.getNature());
            newMemberGroupPurchaseDO.setUserId(oldMemberGroupPurchaseDO.getUserId());
            newMemberGroupPurchaseDO.setMemberId(newMemberGroupPurchaseItemDO.getMemberId());
            newMemberGroupPurchaseDO.setMemberWxUserId(newMemberGroupPurchaseItemDO.getMemberWxUserId());
            newMemberGroupPurchaseDO.setActivityId(oldMemberGroupPurchaseDO.getActivityId());
            this.computeGroupPurchaseGoods(newMemberGroupPurchaseDO);
            memberGroupPurchaseMapper.insert(newMemberGroupPurchaseDO);
        }

        /**
         * 处理旧的主团受影响的订单
         */
        LambdaQueryWrapper<OrderDO> orderLqw = Wrappers.lambdaQuery(OrderDO.class);
        orderLqw.eq(OrderDO::getGroupPurchaseId,oldMemberGroupPurchaseDO.getId()).in(OrderDO::getStatus,1,2,5);
        List<OrderDO> orderDOS = orderMapper.selectList(orderLqw);
        if (orderDOS != null && orderDOS.size() > 0) {
            for (OrderDO aDo : orderDOS) {
                if (newMemberGroupPurchaseItemDO != null) {
                    aDo.setGroupPurchaseGoodsItemId(newMemberGroupPurchaseDO.getGroupPurchaseGoodsItemId());
                    aDo.setGroupPurchaseId(newMemberGroupPurchaseDO.getId());
                } else {
                    aDo.setGroupPurchaseGoodsItemId(oldMemberGroupPurchaseDO.getGroupPurchaseGoodsItemId());
                }
            }
            orderMapper.updateBatchById(orderDOS);
        }

        /**
         * 处理受影响的本人订单
         */
        orderDO.setGroupPurchaseId(targetMemberGroupPurchaseDO.getId());
        orderMapper.updateById(orderDO);

        /**
         * 处理变动之后新入的团
         */
        oldMemberGroupPurchaseItemDO.setGroupPurchaseId(targetMemberGroupPurchaseDO.getId());
        oldMemberGroupPurchaseItemDO.setIdentity(2);
        memberGroupPurchaseItemMapper.updateById(oldMemberGroupPurchaseItemDO);

        targetMemberGroupPurchaseDO.setPersonnelNumber(targetMemberGroupPurchaseDO.getPersonnelNumber() + 1);
        this.computeGroupPurchaseGoods(targetMemberGroupPurchaseDO);
        memberGroupPurchaseMapper.updateById(targetMemberGroupPurchaseDO);

        /**
         * 处理新的主团受影响的订单
         */
        LambdaQueryWrapper<OrderDO> newOrderLqw = Wrappers.lambdaQuery(OrderDO.class);
        newOrderLqw.eq(OrderDO::getGroupPurchaseId,targetMemberGroupPurchaseDO.getId()).in(OrderDO::getStatus,1,2,5);
        List<OrderDO> newOrderDOS = orderMapper.selectList(newOrderLqw);
        if (newOrderDOS != null && newOrderDOS.size() > 0) {
            for (OrderDO newOrderDO : newOrderDOS) {
                newOrderDO.setGroupPurchaseGoodsItemId(targetMemberGroupPurchaseDO.getGroupPurchaseGoodsItemId());
            }
            orderMapper.updateBatchById(newOrderDOS);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editEnroll(OrderDO dto) {
        OrderDO orderDO = orderMapper.selectById(dto.getId());
        if (orderDO != null) {
            orderDO.setEnrollName(dto.getEnrollName());
            orderDO.setEnrollMobile(dto.getEnrollMobile());
            orderDO.setEnrollOther(dto.getEnrollOther());
            orderDO.setOptionalIdentity(dto.getOptionalIdentity());
            return orderMapper.updateById(orderDO) > 0;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean virtual(Long orderId, MemberGroupPurchaseDO dto) {
        if (dto.getVirtualPersonnelNumber() == null) {
            throw new ServiceException("虚拟人数不能为空");
        }
        /**
         * 目标团信息
         */
        MemberGroupPurchaseDO targetMemberGroupPurchaseDO = memberGroupPurchaseMapper.selectById(dto.getId());
        if (targetMemberGroupPurchaseDO == null) {
            throw new ServiceException("拼团不存在");
        }
        if (targetMemberGroupPurchaseDO.getStatus() == 3 && Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0) == 0) {
            throw new ServiceException("该团人员已满，请勿调整虚拟人员");
        }

//        /**
//         * 订单数据
//         */
//        OrderDO orderDO = orderMapper.selectById(orderId);
//        if (orderDO == null) {
//            throw new ServiceException("该用户订单异常，不支持移团");
//        }

        /**
         * 最大人数
         */
        LambdaQueryWrapper<GroupPurchaseGoodsItemDO> goodsItemWrapper = Wrappers.lambdaQuery(GroupPurchaseGoodsItemDO.class);
        goodsItemWrapper.eq(GroupPurchaseGoodsItemDO::getGroupPurchaseGoodsId,targetMemberGroupPurchaseDO.getGroupPurchaseGoodsId())
            .orderByDesc(GroupPurchaseGoodsItemDO::getConstituteNumber);
        List<GroupPurchaseGoodsItemDO> goodsItemDOS = groupPurchaseGoodsItemMapper.selectList(goodsItemWrapper);
        if (goodsItemDOS == null || goodsItemDOS.size() <= 0) {
            throw new ServiceException("当前活动不存在拼团商品");
        }

        if (((targetMemberGroupPurchaseDO.getPersonnelNumber() - Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0)) + dto.getVirtualPersonnelNumber()) >= goodsItemDOS.get(0).getConstituteNumber()) {
            throw new ServiceException("虚拟人数不能设置成满团人数或超过满团人数");
        }

        /**
         * 判断调整的虚拟人数是否大于当前的虚拟人数
         */
        Integer virtualDifference = 0;
        if (dto.getVirtualPersonnelNumber() < Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0)) {
           virtualDifference = Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0) - dto.getVirtualPersonnelNumber();

            /**
             * 查询拼团内信息列表 （删除多余的虚拟人员）
             */
            LambdaQueryWrapper<MemberGroupPurchaseItemDO> oldLqw = Wrappers.lambdaQuery(MemberGroupPurchaseItemDO.class);
            oldLqw.eq(MemberGroupPurchaseItemDO::getGroupPurchaseId,targetMemberGroupPurchaseDO.getId())
                .eq(MemberGroupPurchaseItemDO::getIsNullify,0)
                .eq(MemberGroupPurchaseItemDO::getIsVirtual,1)
                .orderByAsc(MemberGroupPurchaseItemDO::getCreateTime);
            List<MemberGroupPurchaseItemDO> oldPurchaseItemDOS = memberGroupPurchaseItemMapper.selectList(oldLqw);
            if (oldPurchaseItemDOS.size() > 0 && oldPurchaseItemDOS.size() > virtualDifference) {
                List<MemberGroupPurchaseItemDO> itemDOList = new ArrayList<>();
                for (int i = 0; i < virtualDifference; i++) {
                    MemberGroupPurchaseItemDO memberGroupPurchaseItemDO = oldPurchaseItemDOS.get(i);
                    memberGroupPurchaseItemDO.setIsNullify(1);
                    itemDOList.add(memberGroupPurchaseItemDO);
                }
                if (itemDOList.size() > 0) {
                    memberGroupPurchaseItemMapper.updateBatchById(itemDOList);
                }
            }
            targetMemberGroupPurchaseDO.setPersonnelNumber(targetMemberGroupPurchaseDO.getPersonnelNumber() - virtualDifference);
        } else if (dto.getVirtualPersonnelNumber() > Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0)) {
            virtualDifference = dto.getVirtualPersonnelNumber() - Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0);
            /**
             * 给虚拟人员添加 item 信息 （补充差额）
            */
            List<MemberGroupPurchaseItemDO> itemDOList = new ArrayList<>();
            for (int i = 0; i < virtualDifference; i++) {
                String chineseName = RandomName.randomName(true,new Random().nextInt(2) + 2);
                MemberGroupPurchaseItemDO memberGroupPurchaseItemDO = new MemberGroupPurchaseItemDO();
                memberGroupPurchaseItemDO.setGroupPurchaseId(targetMemberGroupPurchaseDO.getId());
                memberGroupPurchaseItemDO.setIdentity(2);
                memberGroupPurchaseItemDO.setIsVirtual(1);
                memberGroupPurchaseItemDO.setCreateTime(DateUtil.getDateTime());
                memberGroupPurchaseItemDO.setVirtualNickname(chineseName);
                itemDOList.add(memberGroupPurchaseItemDO);
            }
            if (itemDOList.size() > 0) {
                memberGroupPurchaseItemMapper.insertBatch(itemDOList);
            }
            targetMemberGroupPurchaseDO.setPersonnelNumber(targetMemberGroupPurchaseDO.getPersonnelNumber() + virtualDifference);
        }

        /**
         * 处理主团新的商品id
         */
        targetMemberGroupPurchaseDO.setVirtualPersonnelNumber(dto.getVirtualPersonnelNumber());
        this.computeGroupPurchaseGoods(targetMemberGroupPurchaseDO);
        memberGroupPurchaseMapper.updateById(targetMemberGroupPurchaseDO);

        /**
         * 处理新的主团受影响的订单
         */
        LambdaQueryWrapper<OrderDO> newOrderLqw = Wrappers.lambdaQuery(OrderDO.class);
        newOrderLqw.eq(OrderDO::getGroupPurchaseId,targetMemberGroupPurchaseDO.getId()).in(OrderDO::getStatus,1,2,5);
        List<OrderDO> newOrderDOS = orderMapper.selectList(newOrderLqw);
        if (newOrderDOS != null && newOrderDOS.size() > 0) {
            for (OrderDO newOrderDO : newOrderDOS) {
                newOrderDO.setGroupPurchaseGoodsItemId(targetMemberGroupPurchaseDO.getGroupPurchaseGoodsItemId());
            }
            orderMapper.updateBatchById(newOrderDOS);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.SERIALIZABLE)
    public boolean batchVirtual(BatchVirtualBO bo) {
        if (bo.getIds().length > 0) {
            if (bo.getVirtualPersonnelNumber() == null) {
                throw new ServiceException("虚拟人数不能为空");
            }
            for (Long id : bo.getIds()) {
                /**
                 * 目标团信息
                 */
                MemberGroupPurchaseDO targetMemberGroupPurchaseDO = memberGroupPurchaseMapper.selectById(id);
                if (targetMemberGroupPurchaseDO == null) {
                    throw new ServiceException("拼团不存在");
                }
                if (targetMemberGroupPurchaseDO.getStatus() == 3 && Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0) == 0) {
                    throw new ServiceException("该团人员已满，请勿调整虚拟人员");
                }
                /**
                 * 最大人数
                 */
                LambdaQueryWrapper<GroupPurchaseGoodsItemDO> goodsItemWrapper = Wrappers.lambdaQuery(GroupPurchaseGoodsItemDO.class);
                goodsItemWrapper.eq(GroupPurchaseGoodsItemDO::getGroupPurchaseGoodsId,targetMemberGroupPurchaseDO.getGroupPurchaseGoodsId())
                    .orderByDesc(GroupPurchaseGoodsItemDO::getConstituteNumber);
                List<GroupPurchaseGoodsItemDO> goodsItemDOS = groupPurchaseGoodsItemMapper.selectList(goodsItemWrapper);
                if (goodsItemDOS == null || goodsItemDOS.size() <= 0) {
                    throw new ServiceException("当前活动不存在拼团商品");
                }

                if (((targetMemberGroupPurchaseDO.getPersonnelNumber() - Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0)) + bo.getVirtualPersonnelNumber()) >= goodsItemDOS.get(0).getConstituteNumber()) {
                    throw new ServiceException("虚拟人数不能设置成满团人数或超过满团人数");
                }

                /**
                 * 判断调整的虚拟人数是否大于当前的虚拟人数
                 */
                Integer virtualDifference = 0;
                if (bo.getVirtualPersonnelNumber() < Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0)) {
                    virtualDifference = Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0) - bo.getVirtualPersonnelNumber();

                    /**
                     * 查询拼团内信息列表 （删除多余的虚拟人员）
                     */
                    LambdaQueryWrapper<MemberGroupPurchaseItemDO> oldLqw = Wrappers.lambdaQuery(MemberGroupPurchaseItemDO.class);
                    oldLqw.eq(MemberGroupPurchaseItemDO::getGroupPurchaseId,targetMemberGroupPurchaseDO.getId())
                        .eq(MemberGroupPurchaseItemDO::getIsNullify,0)
                        .eq(MemberGroupPurchaseItemDO::getIsVirtual,1)
                        .orderByAsc(MemberGroupPurchaseItemDO::getCreateTime);
                    List<MemberGroupPurchaseItemDO> oldPurchaseItemDOS = memberGroupPurchaseItemMapper.selectList(oldLqw);
                    if (oldPurchaseItemDOS.size() > 0 && oldPurchaseItemDOS.size() > virtualDifference) {
                        List<MemberGroupPurchaseItemDO> itemDOList = new ArrayList<>();
                        for (int i = 0; i < virtualDifference; i++) {
                            MemberGroupPurchaseItemDO memberGroupPurchaseItemDO = oldPurchaseItemDOS.get(i);
                            memberGroupPurchaseItemDO.setIsNullify(1);
                            itemDOList.add(memberGroupPurchaseItemDO);
                        }
                        if (itemDOList.size() > 0) {
                            memberGroupPurchaseItemMapper.updateBatchById(itemDOList);
                        }
                    }
                    targetMemberGroupPurchaseDO.setPersonnelNumber(targetMemberGroupPurchaseDO.getPersonnelNumber() - virtualDifference);
                } else if (bo.getVirtualPersonnelNumber() > Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0)) {
                    virtualDifference = bo.getVirtualPersonnelNumber() - Convert.toInt(targetMemberGroupPurchaseDO.getVirtualPersonnelNumber(),0);
                    /**
                     * 给虚拟人员添加 item 信息 （补充差额）
                     */
                    List<MemberGroupPurchaseItemDO> itemDOList = new ArrayList<>();
                    for (int i = 0; i < virtualDifference; i++) {
                        String chineseName = RandomName.randomName(true,new Random().nextInt(2) + 2);
                        MemberGroupPurchaseItemDO memberGroupPurchaseItemDO = new MemberGroupPurchaseItemDO();
                        memberGroupPurchaseItemDO.setGroupPurchaseId(targetMemberGroupPurchaseDO.getId());
                        memberGroupPurchaseItemDO.setIdentity(2);
                        memberGroupPurchaseItemDO.setIsVirtual(1);
                        memberGroupPurchaseItemDO.setCreateTime(DateUtil.getDateTime());
                        memberGroupPurchaseItemDO.setVirtualNickname(chineseName);
                        itemDOList.add(memberGroupPurchaseItemDO);
                    }
                    if (itemDOList.size() > 0) {
                        memberGroupPurchaseItemMapper.insertBatch(itemDOList);
                    }
                    targetMemberGroupPurchaseDO.setPersonnelNumber(targetMemberGroupPurchaseDO.getPersonnelNumber() + virtualDifference);
                }

                /**
                 * 处理主团新的商品id
                 */
                targetMemberGroupPurchaseDO.setVirtualPersonnelNumber(bo.getVirtualPersonnelNumber());
                this.computeGroupPurchaseGoods(targetMemberGroupPurchaseDO);
                memberGroupPurchaseMapper.updateById(targetMemberGroupPurchaseDO);

                /**
                 * 处理新的主团受影响的订单
                 */
                LambdaQueryWrapper<OrderDO> newOrderLqw = Wrappers.lambdaQuery(OrderDO.class);
                newOrderLqw.eq(OrderDO::getGroupPurchaseId,targetMemberGroupPurchaseDO.getId()).in(OrderDO::getStatus,1,2,5);
                List<OrderDO> newOrderDOS = orderMapper.selectList(newOrderLqw);
                if (newOrderDOS != null && newOrderDOS.size() > 0) {
                    for (OrderDO newOrderDO : newOrderDOS) {
                        newOrderDO.setGroupPurchaseGoodsItemId(targetMemberGroupPurchaseDO.getGroupPurchaseGoodsItemId());
                    }
                    orderMapper.updateBatchById(newOrderDOS);
                }
            }
        }
        return true;
    }

    /**
     * 计算主团信息
     */
    public void computeGroupPurchaseGoods(MemberGroupPurchaseDO memberGroupPurchaseDO) {
        Long groupPurchaseGoodsItemId = 0L;
        Integer maxPersonnelNumber = 0;
        //当前拼团下一个商品阶梯id
        Long nextGroupPurchaseGoodsItemId = 0L;
        Integer groupPurchaseStatus = -1;
        /**
         * 阶梯商品列表
         */
        LambdaQueryWrapper<GroupPurchaseGoodsItemDO> goodsItemWrapper = Wrappers.lambdaQuery(GroupPurchaseGoodsItemDO.class);
        goodsItemWrapper.eq(GroupPurchaseGoodsItemDO::getGroupPurchaseGoodsId,memberGroupPurchaseDO.getGroupPurchaseGoodsId())
            .orderByAsc(GroupPurchaseGoodsItemDO::getConstituteNumber);
        List<GroupPurchaseGoodsItemDO> goodsItemDOS = groupPurchaseGoodsItemMapper.selectList(goodsItemWrapper);
        if (goodsItemDOS == null || goodsItemDOS.size() <= 0) {
            throw new ServiceException("当前活动不存在拼团商品");
        }
        if (memberGroupPurchaseDO.getPersonnelNumber() > 0) {
            if (goodsItemDOS != null && goodsItemDOS.size() > 0) {
                for (GroupPurchaseGoodsItemDO goodsItemDO : goodsItemDOS) {
                    if (memberGroupPurchaseDO.getPersonnelNumber() >= goodsItemDO.getConstituteNumber()) {
                        groupPurchaseGoodsItemId = goodsItemDO.getId();
                        maxPersonnelNumber = goodsItemDO.getConstituteNumber();
                        nextGroupPurchaseGoodsItemId = goodsItemDO.getId();
                    } else {
                        nextGroupPurchaseGoodsItemId = goodsItemDO.getId();
                        break;
                    }
                }
            }
            if (groupPurchaseGoodsItemId == 0) {
                groupPurchaseStatus = 1;
            } else if (groupPurchaseGoodsItemId != 0 && (!groupPurchaseGoodsItemId.equals(nextGroupPurchaseGoodsItemId))) {
                groupPurchaseStatus = 2;
            } else if (groupPurchaseGoodsItemId != 0 && (groupPurchaseGoodsItemId.equals(nextGroupPurchaseGoodsItemId))) {
                groupPurchaseStatus = 3;
            }
        }
        memberGroupPurchaseDO.setMaxPersonnelNumber(maxPersonnelNumber);
        memberGroupPurchaseDO.setStatus(groupPurchaseStatus);
        memberGroupPurchaseDO.setGroupPurchaseGoodsItemId(groupPurchaseGoodsItemId);
        memberGroupPurchaseDO.setNextGroupPurchaseGoodsItemId(nextGroupPurchaseGoodsItemId);
    }
}
